# 用户服务
from models import db, User
from common.response import APIResponse
import bcrypt

class UserService:
    @staticmethod
    def get_user_by_id(user_id):
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return APIResponse.not_found('User not found')
        return APIResponse.success(user.to_dict())

    @staticmethod
    def get_all_users(args):
        # 分页查询
        page = args.get('page', 1, type=int)
        per_page = args.get('pageSize', 10, type=int)
        # 根据昵称查询
        nickname = args.get('nickname')
        if nickname:
            users = User.query.filter(User.nickname.like(f'%{nickname}%')).paginate(page=page, per_page=per_page, error_out=False)
        else:
            users = User.query.paginate(page=page, per_page=per_page, error_out=False)
        return APIResponse.success({
            'items': [user.to_dict() for user in users.items],
            'total': users.total,
        })

    @staticmethod
    def create_user(data):
        # 验证必填字段
        required_fields = ['name', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')

        # 密码加密
        password_hash = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())

        # 创建新用户
        new_user = User(
            name=data.get('name'),
            gender=data.get('gender', 0),
            role=data.get('role', 0),
            age=data.get('age',0),
            nickname=data.get('nickname','默认用户'),
            password=password_hash.decode('utf-8'),
            profile_code=data.get('profile_code','默认用户'),
            head = data.get('head','')
        )

        try:
            new_user.save()
            return APIResponse.success(new_user.to_dict(), 'User created successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)

    @staticmethod
    def update_user(user_id, data):
        user = User.query.filter_by(id=user_id).first()
        if not user:
            return APIResponse.not_found('User not found')

        # 检查更新的昵称是否已存在
        if 'nickname' in data and data['nickname'] != user.nickname:
            if User.query.filter_by(nickname=data['nickname']).first():
                return APIResponse.fail('Nickname already exists', 10002)
            user.nickname = data['nickname']

        # 更新其他字段
        if 'name' in data:
            user.name = data['name']
        if 'gender' in data:
            user.gender = data['gender']
        if 'role' in data:
            user.role = data['role']
        if 'age' in data:
            user.age = data['age']
        if 'profile_code' in data:
            user.profile_code = data['profile_code']
        if 'password' in data and data['password']:
            # 密码加密
            password_hash = bcrypt.hashpw(data['password'].encode('utf-8'), bcrypt.gensalt())
            user.password = password_hash.decode('utf-8')
        if "head" in data:
            user.head = data['head']

        try:
            user.save()
            return APIResponse.success(user.to_dict(), 'User updated successfully')
        except Exception as e:
            db.session.rollback()
            return APIResponse.fail(f'Database error: {str(e)}', 10003)
    
    @staticmethod
    def login_user(data):
        # 验证必填字段
        required_fields = ['name', 'password']
        for field in required_fields:
            if field not in data or not data[field]:
                return APIResponse.validate_error(f'{field} is required')
                
        # 查找用户
        user = User.query.filter_by(name=data['name']).first()
        if not user:
            return APIResponse.fail('User not found', 20001)
        
        # 验证密码
        if not bcrypt.checkpw(data['password'].encode('utf-8'), user.password.encode('utf-8')):
            return APIResponse.fail('Incorrect password', 20002)
                
        # 登录成功
        return APIResponse.success(user.to_dict(), 'Login successful')